package dao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import entities.Product;

public class ProductDaoImpl implements ProductDao, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8579605002423625103L;
	private EntityManagerFactory factory;
	private static ProductDaoImpl instance;

	private ProductDaoImpl() {
		factory = Persistence.createEntityManagerFactory("myPU");
		addProducts();
	}

	public static ProductDaoImpl getInstance() {
		if (instance == null) {
			instance = new ProductDaoImpl();
		}
		return instance;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Product> getProducten(String productSoort) {
		Query q = factory.createEntityManager().createQuery(
				"SELECT p from Product p", Product.class);
		return q.getResultList();
	}

	@Override
	public Product getProduct(int productCode) {
		Query q = factory.createEntityManager().createQuery(
				"SELECT p from Product p WHERE p.productCode =:productcode",
				Product.class);
		q.setParameter("productcode", productCode);
		return (Product) q.getSingleResult();
	}

	public void addProducts() {
		EntityManager em = factory.createEntityManager();
		try {
			em.getTransaction().begin();
			Product p1 = new Product();
			p1.setAll(1, 19.95, "Product1");
			Product p2 = new Product();
			p2.setAll(2, 19.95, "Product2");
			Product p3 = new Product();
			p3.setAll(3, 19.95, "Product3");
			Product p4 = new Product();
			p4.setAll(4, 19.95, "Product4");
			em.persist(p1);
			em.persist(p2);
			em.persist(p3);
			em.persist(p4);
			em.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
